﻿using System;
using System.Collections.Generic;
using Core.Utils;

namespace Core.Animation {
    public class AnimationProcessTaskQueue {
        public List<AnimationProcess> TaskQueue {
            get {
                return mTaskQueue;
            }
        }
        private List<AnimationProcess> mTaskQueue = new();
        
        public void AddLast(AnimationProcess process) {
            mTaskQueue.Add(process);
        }
        public void Clear() {
            for (int i = 0; i < mTaskQueue.Count; ++i) {
                var process = mTaskQueue[i];
                process.Animation.Stop(process.AnimName);
                process.End?.Invoke();
            }
        }
    }
    public class AnimationProcess : IResetable {
        public Action Start;
        public Action Complete;
        public Action End;

        public IAnimation Animation {
            get;
            private set;
        }

        public bool IsStarted {
            get;
            private set;
        }

        public bool IsEnd {
            get;
            private set;
        }

        public string AnimName {
            get {
                return mAnimName;
            }
        }
        
        private string mAnimName;
        private float mDuration;
        private bool mIsLoop;
        private float mDelay;
        private float mCurTime;
        public void SetData(IAnimation anim,string name,bool isLoop,float delay = .0f) {
            Animation = anim;
            mDuration = anim.GetDuration(name);
            mIsLoop = isLoop;
            mAnimName = name;
            mDelay = .0f;
        }
        
        public void Reset() {
            Start = null;
            Complete = null;
            End = null;
            Animation = null;
            mDuration = .0f;
            mDelay = .0f;
            mIsLoop = false;

            IsStarted = false;
            IsEnd = false;
            mCurTime = .0f;
        }

        public void Update(float deltaTime) {
            mCurTime += deltaTime;
            if (!IsStarted && mCurTime < mDelay) {
                return;
            }
            mCurTime -= mDelay;
            if (!IsStarted) {
                IsStarted = true;
                Start?.Invoke();
            }
            if (mCurTime >= mDuration) {
                Complete?.Invoke();
                if (mIsLoop) {
                    mCurTime %= mDuration;
                } else {
                    IsEnd = true;
                    End?.Invoke();
                }
            }
        }
    }
}